/************************* COMMON FUNCTIONS **************************/
var Common = {};
/**
 * Encode special characters in a plain-text string for display as HTML.
 * TODO: escape, urlencode
 */
Common.checkPlain = function (str) {
	var character, regex,
	replace = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' };
	str = String(str);
	for (character in replace) {
		if (replace.hasOwnProperty(character)) {
			regex = new RegExp(character, 'g');
			str = str.replace(regex, replace[character]);
		}
	}
	return str;
}; 
/**
 * Encode special characters in a plain-text string for display as HTML.
 * Example: Common.nl2br('Onen\nTwo\nThree'); //'Onen<br />Two<br />Three'
 */
Common.nl2br = function (str, is_xhtml) {   
    var breakTag = (is_xhtml || typeof(is_xhtml) === 'undefined') ? '<br />' : '<br>';    
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
/**
 * Strip whitespace (or other characters) from the beginning and end of a string
 * Example: Common.trim('    Kevin van Zonneveld    '); //'Kevin van Zonneveld'
 * 			Common.trim('Hello World', 'Hdle'); //'o Wor'
 */
Common.trim = function (str, charlist) {
	var whitespace, l = 0,
	i = 0;
	str += '';
	
	if (!charlist) {
		// default list
		whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
	} else {
		// preg_quote custom list
		charlist += '';
		whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
	}
	
	//trim left
	l = str.length;
	for (i = 0; i < l; i++) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(i);
			break;
		}
	}
	
	//trim right
	l = str.length;
	for (i = l - 1; i >= 0; i--) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	
	return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}
Common.ltrim = function (str, charlist) {
	charlist = !charlist ? ' \\s\u00A0' : (charlist + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
	var re = new RegExp('^[' + charlist + ']+', 'g');
	return (str + '').replace(re, '');
}
Common.rtrim = function (str, charlist) {
	charlist = !charlist ? ' \\s\u00A0' : (charlist + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\\$1');
	var re = new RegExp('[' + charlist + ']+$', 'g');
	return (str + '').replace(re, '');
}
/**
 * Strip HTML and PHP tags from a string
 * Example: Common.strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>'); //'Kevin <b>van</b> <i>Zonneveld</i>'
 * 			Common.strip_tags('One <br/> Two'); //'One Two'
 */
Common.strip_tags = function (input, allowed) {
	// making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
	allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
	var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
	commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
	return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
		return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
	});
}
/**
 * Check if an email is valid or not?
 * Example: Common.isEmail('anh.dang@mail.careerbuilder.vn'); //Valid
 */
Common.isEmail = function(email) {
	var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
	if (filter.test(email)) {
		return true;
	}
	else {
		return false;
	}
}
Common.transliterate = function (source, settings) {
	var maxlength = 128;
	var pattern = '[^a-z0-9-]+';
	var replase = '-'
	var rx = new RegExp(pattern, 'g');
	return source.toLowerCase().replace(rx, replase).substr(0, maxlength);
} 

function genAutoCode(args){
	if(args.lock == true){
		$(args.labelTarget).show();
		$(args.labelSource).hide();	
		return;	
	}
	
	var strInput = Common.transliterate($(args.source).val());
	$(args.target).html(strInput).val(strInput);
	if(strInput != ''){
		$(args.labelSource).show();	
	}else{
		$(args.labelTarget).hide();	
	}
	//add event
	$(args.source).bind('change keyup', function(){
		var strInput = Common.transliterate($(args.source).val());
		$(args.target).html(strInput).val(strInput);
		if(strInput != ''){
			$(args.labelSource).show();	
		}else{
			$(args.labelTarget).hide();	
		}
	});
	//
	$(args.button).click(function(){
		$(this).hide();
		$(args.source).unbind('change keyup');	
		$(args.labelSource).hide();
		$(args.labelTarget).show();
	});
}

/* check if browser is IE
   Example: if (isIE()) || if(isIE() < 8)
*/
function isIE() {
  var myNav = navigator.userAgent.toLowerCase();
  return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}

function redirect(url)
{
	window.location = url;
}

function isset(obj) {
    if ((typeof (obj) === 'undefined') || (obj === null))
        return false;
    else
        return true;
};

//AnhDKD: set cookie
function setCookie(c_name,value,exdays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
}

//AnhDKD: get cookie
function getCookie(c_name)
{
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++)
	{
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==c_name)
		{
			return unescape(y);
		}
	}
}

function deleteCookie(c_name) {
    document.cookie = c_name + "=; expires=Thu, 01 Jan 1970 00:00:01 GMT;";
};

/************************* FUNCTIONS **************************/

function show_confirm(msg, msg_ok, msg_cancel)
{
	var r=confirm(msg);
	if (r==true){
		if(msg_ok)
			alert(msg_ok);
	}
	else{
		if(msg_cancel)
			alert(msg_cancel);
	}
	return r;
}

/*Select all checkboxes*/
function selectAll(obj)
{
	$("input:not(:disabled)[type='checkbox']").prop("checked" , obj.checked);
}

/*Get value of selected checkboxes*/
function getSelectedByName(objname){
	var ids = '';
	$("INPUT[name^='"+objname+"'][disabled!='true']").each(function () {
		if($(this).is(':checked'))
			ids += $(this).val() + ',';
	});
	return ids.replace(/[\s,]+$/, '');;
}